﻿//获取长度
function GetLength(val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
        if (val.charCodeAt(i) < 27 || val.charCodeAt(i) > 126) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
}

// 获得cookie值
function GetCookie(nm) {
    var m = null;
    if (window.RegExp) {
        var re = new RegExp(";\\s*" + nm + "=([^;]*)", "i");
        m = re.exec(';' + document.cookie);
    }
    return (m ? unescape(m[1]) : null);
}

// 设置cookie值
function SetCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 86400000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expires + ";path=/";
}

//戴取字符串长度，并保留html标签
function toRightLen(node, num) {
    var node = (node.replace(/<[^>]+>/g, "")).replace(/^\s+|\s+$/g, "");
    var z = /[^\x00-\xff]/g;
    var x = node.replace(z, 'rr');
    var y = node.split("&gt;").length - 1;
    var u = node.split("&lt;").length - 1;
    var n = node.split("&amp;").length - 1;
    var w = node.split("&nbsp;").length - 1;
    num = num + (y + u) * 3 + n * 4 + w * 5;
    var result = '';
    if (x.length < num) {
        return node;
    } else {
        if (node.substr(0, num).replace(z, 'rr').length > num) {
            var cut = Math.floor(num / 2);
            for (var i = cut; i < num; i++) {
                result = node.substr(0, i).replace(z, 'rr').length;
                if (result >= num) {
                    return node.substr(0, i).replace(/^\s+|\s+$/g, "");
                }
            }
        } else {
            return node.substr(0, num).replace(/^\s+|\s+$/g, "");
        }
    }
}
//戴取字符串长度，并保留html标签
function htmlIntercept(num, node) {
    var newvalue, tkey, oldvalue, len, subkey, dd2, pos, sum;
    oldvalue = node;
    len = (oldvalue.replace(/<[^>]+>/g, "")).replace(/[^\x00-\xff]/g, 'rr').length;
    if (len <= num) {
        return oldvalue
    }
    newvalue = toRightLen(oldvalue, num);
    tkey = newvalue.charAt(newvalue.length - 1); //最后字符
    subkey = (newvalue.split(tkey)).length - 1; //次数
    pos = oldvalue.indexOf(tkey);
    sum = (oldvalue.split(tkey)).length;

    for (var i = 1; i <= sum; i++) {
        if (subkey <= i) {
            dd2 = toRightLen(oldvalue.substring(0, pos + 1), num);
            if (dd2 == newvalue) {
                var div = document.createElement('div');
                div.innerHTML = oldvalue.substring(0, pos + 1);
                return div.innerHTML;
            }
            pos = oldvalue.indexOf(tkey, pos + 1);
        }
    }
    return oldvalue;
}